#!/bin/bash

# query_user_login.sh
# 功能说明:
# 1. 查询指定用户或多个用户的登录信息，包括最近登录时间、登录次数和登录状态。
# 2. 如果用户从未登录，会明确标注。
# 3. 支持从命令行传入用户名，或从文件中批量读取用户列表。

# 检查用户的登录信息
query_user_login() {
  local username="$1"

  # 检查用户是否存在
  if ! id "$username" &>/dev/null; then
    echo "User $username does not exist."
    return
  fi

  # 获取用户的最近登录信息
  local last_login=$(lastlog -u "$username" | awk 'NR==2 {print $4, $5, $6}')
  local login_count=$(last "$username" | wc -l)

  if [[ -z "$last_login" || "$last_login" == "**Never logged in**" ]]; then
    echo "User: $username | Last Login: Never logged in | Login Count: 0"
  else
    echo "User: $username | Last Login: $last_login | Login Count: $login_count"
  fi
}

# 从文件批量查询用户
query_users_from_file() {
  local file="$1"

  if [[ ! -f "$file" ]]; then
    echo "File $file does not exist."
    exit 1
  fi

  while IFS= read -r username; do
    [[ -z "$username" || "$username" == \#* ]] && continue
    query_user_login "$username"
  done <"$file"
}

# 主函数
main() {
  if [[ $# -lt 1 ]]; then
    echo "Usage: $0 [username | -f user_file]"
    echo "  username: Specify a single user to query login information."
    echo "  -f user_file: Specify a file containing usernames to query."
    exit 1
  fi

  if [[ "$1" == "-f" ]]; then
    shift
    if [[ -n "$1" ]]; then
      query_users_from_file "$1"
    else
      echo "Error: Missing file name after -f."
      exit 1
    fi
  else
    query_user_login "$1"
  fi
}

# 执行主函数
main "$@"

